package com.common.app.adapter

import android.view.View

import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.common.base.app.extras.getContext


/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：30/6/2023
 *
 * 描述：
 *
 * 修订历史：
 *
 */


class MyHeaderAndFooterAdapter(mAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder?>) :
    RecyclerView.Adapter<RecyclerView.ViewHolder?>() {
    private val headType = 0x11111
    private val normalType = 0x11112
    private val footType = 0x11113
    private var headerView: View? = null
    private var footerView: View? = null
    private val badapter: RecyclerView.Adapter<RecyclerView.ViewHolder?>//目标adapter
    private var mOrientation = -1
    private var loadMoreListener: LoadMoreListener? = null

    init {
        this.badapter = mAdapter
    }

    fun addHeader(header: View?) {
        headerView = header
    }

    fun addFooter(footer: View?) {
        footerView = footer
    }

    //实现加载更多接口
    fun setLoadMoreListener(
        loadMoreListener: LoadMoreListener?,
        recyclerView: RecyclerView?
    ) {
        this.loadMoreListener = loadMoreListener
        recyclerView?.setOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                loadMoreListener?.onScrollStateChang(recyclerView, newState)
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (isSlideToBottom(recyclerView)) {
                    loadMoreListener?.onLoadMore()
                }
            }
        })
    }

    /**
     * 根据头部尾部返回相应的type，这里if else没有简写，方便看逻辑
     *
     * @param position
     * @return
     */
    override fun getItemViewType(position: Int): Int {
        return if (headerView != null && footerView != null) //同时加了头部和尾部
        {
            if (position == 0) //当position为0时，展示header
            {
                headType
            } else if (position == itemCount - 1) //当position为最后一个时，展示footer
            {
                footType
            } else  //其他时候就展示原来adapter的
            {
                if (badapter.itemCount > 1) {
                    badapter.getItemViewType(position)
                } else normalType
            }
        } else if (headerView != null) { //只有头部
            if (position == 0) return headType
            if (badapter.itemCount > 1) {
                badapter.getItemViewType(position)
            } else normalType
        } else if (footerView != null) //只有尾部
        {
            if (position == itemCount - 1) {
                footType
            } else {
                if (badapter.itemCount > 1) {
                    badapter.getItemViewType(position)
                } else normalType
            }
        } else {
            if (badapter.itemCount > 1) {
                badapter.getItemViewType(position)
            } else normalType
        }
    }

    /**
     * 这里就根据getItemViewType返回的值来返回相应的ViewHolder
     * 头部和尾部的ViewHolder只是一个集成RecyclerView.ViewHolder的简单默认类，里面并没有任何处理。
     * 这样就完成了类型的返回了（需注意为什么这样做）
     *
     * @param parent
     * @param viewType
     * @return
     */
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
//        //返回头部的ViewHolder
//        if (viewType == headtype) return HeaderViewHolder(headerView) else if (viewType == foottype) //返回尾部的ViewHolder
//            return FoogerViewHolder(footerView) //其他就直接返回传入的adapter的ViewHolder
//        return badapter.onCreateViewHolder(parent, viewType)

        //返回头部的ViewHolder
        if (viewType == headType)
            return  HeaderViewHolder(headerView?:View(getContext()))
        else if (viewType == footType)//返回尾部的ViewHolder
            return  FoogerViewHolder(footerView?:View(getContext()))//其他就直接返回传入的adapter的ViewHolder
        return badapter.onCreateViewHolder(parent, viewType)
    }

    /**
     * 绑定ViewHolder，当时header或footer时，直接返回，因为不用绑定，
     * 当是传入的adapter时，就直接调用adapter.onBindViewHolder就行了
     *
     * @param holder
     * @param position
     */
    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (footerView != null) {
            footerView?.setOnClickListener {
                if (loadMoreListener != null) {
                    loadMoreListener?.onClickLoadMore()
                }
            }
        }
        if (headerView != null && footerView != null) //有头部和尾部
        {
            if (position == 0) //头部直接返回，无需绑定
            {
                return
            } else if (position == itemCount - 1) //尾部直接返回，也无需绑定
            {
                return
            } else {
                holder.itemView.setOnClickListener(View.OnClickListener { v ->
                    if (loadMoreListener != null) {
                        loadMoreListener?.onItemClick(v, position - 1)
                    }
                })
                badapter.onBindViewHolder(holder, position - 1) //其他就调用adapter的绑定方法
            }
        } else if (headerView != null) {
            if (position == 0) {
                return
            } else {
                holder.itemView.setOnClickListener(View.OnClickListener { v ->
                    if (loadMoreListener != null) {
                        loadMoreListener?.onItemClick(v, position - 1)
                    }
                })
                badapter.onBindViewHolder(holder, position - 1)
            }
        } else if (footerView != null) {
            if (position == itemCount - 1) {
                return
            } else {
                holder.itemView.setOnClickListener(View.OnClickListener { v ->
                    if (loadMoreListener != null) {
                        loadMoreListener?.onItemClick(v, position)
                    }
                })
                badapter.onBindViewHolder(holder, position)
            }
        } else {
            holder.itemView.setOnClickListener(View.OnClickListener { v ->
                if (loadMoreListener != null) {
                    loadMoreListener?.onItemClick(v, position)
                }
            })
            badapter.onBindViewHolder(holder, position)
        }
    }

    /**
     * 返回item的数量，
     *
     * @return
     */
    override fun getItemCount(): Int {
        if (headerView != null && footerView != null) //有头部和尾部，就多了2
        {
            return badapter.itemCount + 2
        } else if (headerView != null) //只有头部多了1
        {
            return badapter.itemCount + 1
        } else if (footerView != null) //只有尾部也多了1
        {
            return badapter.itemCount + 1
        }
        return badapter.itemCount //其他就是默认的值， 不多也不少
    }

    /**
     * 头部的ViewHolder
     */
    private inner class HeaderViewHolder(itemView: View) :
        RecyclerView.ViewHolder(itemView)

    /**
     * 尾部的ViewHolder
     */
    private inner class FoogerViewHolder(itemView: View) :
        RecyclerView.ViewHolder(itemView)

    /**
     * 处理当时Gridview类型的效果时，也把头部和尾部设置成一整行（这就是RecyclerView的其中一个优秀之处，列表的每行可以不同数量的列）
     *
     * @param recyclerView
     */
    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        val layoutManager: RecyclerView.LayoutManager? = recyclerView.layoutManager
        mOrientation = getOrientation(layoutManager)
        if (layoutManager is GridLayoutManager) {
            /**
             * getSpanSize的返回值的意思是：position位置的item的宽度占几列
             * 比如总的是4列，然后头部全部显示的话就应该占4列，此时就返回4
             * 其他的只占一列，所以就返回1，剩下的三列就由后面的item来依次填充。
             */
            layoutManager.spanSizeLookup = object :
                GridLayoutManager.SpanSizeLookup() {
                override fun getSpanSize(position: Int): Int {
                    if (headerView != null && footerView != null) {
                        return if (position == 0) {
                            layoutManager.spanCount
                        } else if (position == itemCount - 1) {
                            layoutManager.spanCount
                        } else {
                            1
                        }
                    } else if (headerView != null) {
                        return if (position == 0) {
                            layoutManager.spanCount
                        } else 1
                    } else if (footerView != null) {
                        return if (position == itemCount - 1) {
                            layoutManager.spanCount
                        } else 1
                    }
                    return 1
                }
            }
        }
    }

    /**
     * 判断是否到底部了
     *
     * @param recyclerView
     * @return
     */
    protected fun isSlideToBottom(recyclerView: RecyclerView?): Boolean {
        if (recyclerView == null) return false
        if (mOrientation == LinearLayoutManager.VERTICAL) {
            if (recyclerView.computeVerticalScrollExtent() + recyclerView.computeVerticalScrollOffset() >= recyclerView.computeVerticalScrollRange()) return true
        } else {
            if (recyclerView.computeHorizontalScrollExtent() + recyclerView.computeHorizontalScrollOffset() >= recyclerView.computeHorizontalScrollRange()) return true
        }
        return false
    }

    /**
     * 加载更多回调接口
     */
    interface LoadMoreListener {
        fun onScrollStateChang(recyclerView: RecyclerView?, newState: Int)
        fun onLoadMore()
        fun onClickLoadMore()
        fun onItemClick(view: View?, position: Int)
    }

    private fun getOrientation(layoutManager: RecyclerView.LayoutManager?): Int {
        var mOrientation = 0
        layoutManager?.let {
            if (layoutManager is LinearLayoutManager) {
                mOrientation = layoutManager.orientation
            }
        }
        return mOrientation
    }
}